import { error, JsonAsset, resources } from "cc";

/**
 * 数据管理器
 */
export default class DataManager
{
    public static readonly  DATA_JSON_PATH : string = "data/";

    public static get Instance() : DataManager {
        if(!this._Instance)
            this._Instance = new DataManager();
        return this._Instance; 
    }
    private static _Instance : DataManager;

    private constructor() {
        
    }

    private dataMap : Map<string,any> = new Map();

    /**
     * DataManager 初始化
     */
    public Init(){

    }

    public async GetData<T>(key:string,dir = DataManager.DATA_JSON_PATH) : Promise<T>{
        let data = this.dataMap.get(key);
        if(!data){
            data = await this.loadData<T>(key,dir);
            this.dataMap.set(key,data);
            return data.json as T;
        }
        return data.json as T;
    }

    private loadData<T>(key : string,dir = DataManager.DATA_JSON_PATH) : Promise<T>{
        let path = dir + key;
        return new Promise<T>((resolve,reject)=>{
            resources.load(path,JsonAsset,(error,jsonAsset)=>
                {
                    if(error){
                        reject("DataManager: Data "+key+" Not Found!")
                    }
                    let data = jsonAsset.json as T;
                    if(!data){
                        reject("DataManager: Data "+key+" Has Wrong Key!")
                    }
                    resolve(data);
                })
        });
    } 

    /**
     * 预加载数据
     */
    public preloadData() : Promise<void>{
        let dirPath = DataManager.DATA_JSON_PATH;
        return new Promise((resolve,reject)=>{
            resources.loadDir(dirPath,JsonAsset,(error,jsonArray)=>{
                if(error){
                    reject("DataManager: Data Dir Load Wrong!")
                }
                for (const json of jsonArray) {
                    this.dataMap.set(json.name,json);
                }
                resolve();
            });
        });
    }

    public TestShowData(){
        console.log(this.dataMap);
    }
}